package io.dirac.controller;

import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.dirac.dto.LoginDto;
import io.dirac.entity.User;
import io.dirac.result.Result;
import io.dirac.service.UserService;
import io.dirac.shiro.JwtUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;

@RestController
public class AccountController {

    @Autowired
    JwtUtils jwtUtils;

    @Autowired
    UserService userService;


    @CrossOrigin
    @PostMapping("/login")
    public Result login(@Validated @RequestBody LoginDto loginDto, HttpServletResponse response) {
        User user = userService.getOne(new QueryWrapper<User>().eq("username", loginDto.getUsername()));
        Assert.notNull(user, "用户不存在");
        if (!user.getPassword().equals(SecureUtil.md5(loginDto.getPassword()))) {
            return Result.fail("密码错误！");
        }
        String jwt = jwtUtils.generateToken(user.getId());
        response.setHeader("Authorization", jwt);
        response.setHeader("Access-Control-Expose-Headers", "Authorization");
        // 用户可以另一个接口
        return Result.success(MapUtil.builder()
                .put("id", user.getId())
                .put("username", user.getUsername())
                .put("authority", user.getAuthority())
                .put("gender", user.getGender())
                .put("birthday", user.getBirthday())
                .put("email", user.getEmail())
                .put("phone", user.getPhone())
                .put("address", user.getAddress())
                .put("status", user.getStatus())
                .put("score", user.getScore())
                .map()
        );
    }

    @CrossOrigin
    @PostMapping("/register")
    public Result register(@Validated @RequestBody User registerUser,
                           HttpServletRequest request,
                           HttpServletResponse response) throws ServletException, IOException {

        System.out.println(registerUser);

        Assert.isNull(userService.getOne(new QueryWrapper<User>().eq("username", registerUser.getUsername())), "用户名已存在");
        Assert.isNull(userService.getOne(new QueryWrapper<User>().eq("email", registerUser.getEmail())), "邮箱已存在");

        User user = new User();
        BeanUtils.copyProperties(registerUser, user);

        user.setPassword(SecureUtil.md5(user.getPassword()));
        userService.save(user);

        LoginDto loginDto = new LoginDto();
        BeanUtils.copyProperties(registerUser, loginDto);

        return Result.success(loginDto);
    }

    @GetMapping("/logout")
    @RequiresAuthentication
    public Result logout() {
        SecurityUtils.getSubject().logout();
        return Result.success(null);
    }
}
